//
//  YWInformationDetailViewController.m
//  maintain
//
//  Created by Kyo on 16/5/20.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWInformationDetailViewController.h"
#import "YWattachment.h"
#import "YWMacro.h"
#import "YWAttachmentsView.h"
//#import "YWAlertView.h"
#import "YWAttachmentManager.h"
#import "YWCommonTool.h"
#import "YWResourceManager.h"
#import "ASProgressPopUpView.h"
#import "UIColor+CustomColors.h"
#import <QuickLook/QuickLook.h>

#define KOpenTag 1102
#define KDownLoadTag 1103
#define KDownLoadingTag 1104
#define KCancelDownLoadTag 1105

@interface YWInformationDetailViewController ()<QLPreviewControllerDataSource>
@property (nonatomic, strong)UIImageView *iconImageView;
@property (nonatomic, strong)UILabel *attachmentNameLabel;
@property (nonatomic, strong)UILabel *attachmentSizeLabel;
@property (nonatomic, strong)UIButton *loadOrOpenButton;
@property (nonatomic, strong) ASProgressPopUpView* progressView;

@end

@implementation YWInformationDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    [self setUpSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setUpSubviews{
    [self.view addSubview:self.iconImageView];
    [self.view addSubview:self.attachmentNameLabel];
    [self.view addSubview:self.attachmentSizeLabel];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.loadOrOpenButton];
    
}
-(UIImageView *)iconImageView{
    if (!_iconImageView) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-70)/2, 100, 80, 80)];
        NSString *typemName = [[self.attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
        imageView.image = [YWAttachmentsView bigImageWithType:typemName];
        _iconImageView = imageView;
    }
    return _iconImageView;
}
-(UILabel *)attachmentNameLabel{
    if (!_attachmentNameLabel) {
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.iconImageView.frame)+30, SCREEN_WIDTH-kMarginW*2, kLabelH*2)];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.numberOfLines = 2;
        nameLabel.text = self.attachment.attachmentName;
        _attachmentNameLabel = nameLabel;
    }
    return _attachmentNameLabel;
}
-(UILabel *)attachmentSizeLabel{
    if (!_attachmentSizeLabel) {
        UILabel *sizeLabel = [[UILabel alloc]initWithFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.attachmentNameLabel.frame)+30, SCREEN_WIDTH-kMarginW*2, kLabelH)];
        sizeLabel.textAlignment = NSTextAlignmentCenter;
        NSString *sizeStr = [YWCommonTool getFileSize:self.attachment.fileSize*1024];
        if (self.attachment.localName){
            sizeLabel.text = [NSString stringWithFormat:@"%@ 已下载",sizeStr];
        }else{
            sizeLabel.text = sizeStr;
        }
        _attachmentSizeLabel = sizeLabel;
    }
    return _attachmentSizeLabel;
}
-(UIButton *)loadOrOpenButton{
    if (!_loadOrOpenButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setFrame:CGRectMake(0, SCREEN_HEIGHT-kButtonH, SCREEN_WIDTH, kButtonH)];
        button.titleLabel.font = kBoldTitleFont;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor customBlueColor]];
        if (self.attachment.localName) {
            [button setTitle:@"打开" forState:UIControlStateNormal];
            button.tag = KOpenTag;
        }else{
            [button setTitle:@"下载" forState:UIControlStateNormal];
            button.tag = KDownLoadTag;
        }
        [button addTarget:self action:@selector(downLoadOrOpenFile:) forControlEvents:UIControlEventTouchUpInside];
        _loadOrOpenButton = button;
    }
    return _loadOrOpenButton;
}
- (ASProgressPopUpView*)progressView
{
    if (!_progressView) {
        ASProgressPopUpView* progressView = [[ASProgressPopUpView alloc] initWithFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.attachmentSizeLabel.frame)+30, SCREEN_WIDTH-kMarginW*2, 20)];
        progressView.popUpViewAnimatedColors = @[ [UIColor customBlueColor] ];
        progressView.popUpViewCornerRadius = 12.0;
        progressView.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:16];
        [progressView showPopUpViewAnimated:YES];
        _progressView = progressView;
        progressView.hidden = YES;
    }
    return _progressView;
}

- (void)downLoadOrOpenFile:(UIButton*)button{
    if (button.tag == KOpenTag) {
        //打开
        [self showAttachment:self.attachment];
    }else if (button.tag == KDownLoadTag){
        //下载
        NSString *tip = @"是否下载 (建议您在wifi环境下下载)";
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:tip preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            button.tag = KDownLoadingTag;
            [button setTitle:@"正在下载" forState:UIControlStateNormal];
            button.userInteractionEnabled = NO;
            self.progressView.hidden = NO;
            
            NSString *typemName = [[self.attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
            NSString* documentName = self.attachment.attachmentName?:[NSString stringWithFormat:@"%@.%@", [YWCommonTool randStringId],typemName];
            NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:documentName];
            [[YWAttachmentManager shareManager] downloadFile:self.attachment.downLoadUrl toFilePath:fullPath progressBlock:^(float progress) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.progressView setProgress:progress animated:YES];
                });
            } completeBlock:^(BOOL success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (success) {
                        //保存全路径到数据库
                        self.attachment.localName = documentName;
                        BOOL save = [[YWAttachmentManager shareManager] updateAttachmenLocalNameWithAttachment:self.attachment];
                        if (save) {
                            [self loadSuccessWithButton:button];
                        }else{
                            [self loadFailedWithButton:button];
                        }
                    }else{
                        [self loadFailedWithButton:button];
                    }
                });
            }];
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        //取消
        //正在下载
    }
}
- (void)loadSuccessWithButton:(UIButton*)button{
    button.userInteractionEnabled = YES;
    [button setTitle:@"打开" forState:UIControlStateNormal];
    button.tag = KOpenTag;
    NSString *sizeStr = [YWCommonTool getFileSize:self.attachment.fileSize*1024];
    self.attachmentSizeLabel.text = [NSString stringWithFormat:@"%@ 已下载",sizeStr];
}
- (void)loadFailedWithButton:(UIButton*)button{
    button.userInteractionEnabled = YES;
    [YWCommonTool showTextHUDWithContent:@"下载失败，请重试"];
    [button setTitle:@"下载" forState:UIControlStateNormal];
    button.tag = KDownLoadTag;
}

-(void)showAttachment:(YWattachment *)attachment{
    _attachment = attachment;
    if (_attachment.localName) {
        QLPreviewController *previewer = [[QLPreviewController alloc] init];
        [previewer setDataSource:self];
        [previewer setCurrentPreviewItemIndex:0];
        [self.navigationController pushViewController:previewer animated:YES];
    }
}
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    return 1;
}

-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    NSString *path = [[YWResourceManager shareManager] fileCachePathFromResourcePath:_attachment.localName];
    NSURL *url = [NSURL fileURLWithPath:path];
    return url;
}

@end
